package com.app.studyroom.model;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ClassroomDeserializer implements JsonDeserializer<Classroom> {
    @Override
    public Classroom deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject obj = json.getAsJsonObject();
        Classroom classroom = new Classroom();

        // 解析教室名称
        classroom.setName(obj.get("name").getAsString());

        // 解析 layout
        List<List<LayoutElement>> layout = new ArrayList<>();
        JsonArray rows = obj.getAsJsonArray("layout");

        for (JsonElement rowElement : rows) {
            JsonArray rowArray = rowElement.getAsJsonArray();
            List<LayoutElement> row = new ArrayList<>();
            for (JsonElement cell : rowArray) {
                if (cell.isJsonNull()) {
                    row.add(null);
                } else {
                    JsonObject cellObj = cell.getAsJsonObject();
                    LayoutElement e = context.deserialize(cell, LayoutElement.class);
                    if (cellObj.has("seatStatus")) {
                        e.seatStatus = cellObj.get("seatStatus").getAsString();
                    }
                    row.add(e);
                }
            }
            layout.add(row);
        }
        classroom.setLayout(layout);

        // ✅ 新增解析 frames 字段
        if (obj.has("frames") && obj.get("frames").isJsonArray()) {
            JsonArray framesArray = obj.getAsJsonArray("frames");
            List<Classroom.FrameOverlay> frameList = new ArrayList<>();

            for (JsonElement frameElement : framesArray) {
                JsonObject f = frameElement.getAsJsonObject();
                Classroom.FrameOverlay overlay = new Classroom.FrameOverlay();
                overlay.x = f.get("x").getAsInt();
                overlay.y = f.get("y").getAsInt();
                overlay.width = f.get("width").getAsInt();
                overlay.height = f.get("height").getAsInt();
                overlay.borderColor = f.has("borderColor") ? f.get("borderColor").getAsString() : "#FF0000";
                overlay.borderWidth = f.has("borderWidth") ? f.get("borderWidth").getAsInt() : 4;
                frameList.add(overlay);
            }
            classroom.setFrames(frameList);
        }

        return classroom;
    }
}
